﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Aletfa.LightManager.Console;
using Aletfa.LightManager.Effects;

namespace Aletfa.LightManager
{
    /// <summary>
    /// Interaction logic for ConsoleControl.xaml
    /// </summary>
    internal partial class ConsoleControl : UserControl
    {
        private string HtmlHeader { get; set; }

        private string Html { get; set; }

        private ConsoleParser Parser { get; set; } 

        public ConsoleControl()
        {
            InitializeComponent();
        }

        public void Initialize(GameManager manager)
        {
            manager.LogNeeded += this.Log;
            this.Parser = new ConsoleParser(manager);
            this.Parser.LogClearRequested += this.ClearLog;
            this.Parser.LogRequested += this.Log;

            this.HtmlHeader = System.IO.File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "console.css"), Encoding.UTF8);
            this.HtmlHeader = string.Format("<head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'><style>{0}</style></head>", this.HtmlHeader);
            this.ClearLog();
        }

        private void ClearLog()
        {
            this.Html = this.HtmlHeader;
            this.wbLog.NavigateToString(this.Html);
        }

        private void Log(string text)
        {
            if (string.IsNullOrEmpty(text)) return;
            this.Html = this.HtmlHeader + string.Format("<font class='time'>{0}: </font>{1}<br />", DateTime.Now.ToString("HH:mm"), text) + this.Html;
            this.wbLog.NavigateToString(this.Html);
            //this.BeginInvoke(new GenericDelegate<string>(this.LogAsync), text);
        }

        private void txtCommand_KeyDown(object sender, KeyEventArgs e)
        {
            this.txtCommand.Text = this.txtCommand.Text.Replace("\r\n", "");
            if (e.Key == Key.Enter)
            {
                if (string.IsNullOrEmpty(this.txtCommand.Text)) return;
                this.Parser.ParseCommand(this.txtCommand.Text);
                this.txtCommand.Text = "";
                this.txtCommand.Select(0, 0);
            }
        }
    }
}
